package com.dizner.diassistant.ui.home

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.dizner.diassistant.R
import com.dizner.diassistant.database.AppDatabase
import com.dizner.diassistant.database.DBOptionManager
import com.dizner.diassistant.dataentry.BloodPressureHistoryEntry
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import kotlinx.android.synthetic.main.fragment_home.*
import java.text.SimpleDateFormat
import java.util.*


class HomeFragment : Fragment() {

    private val TAG: String = "HomeFragment"
    private lateinit var homeViewModel: HomeViewModel
    private lateinit var appDatabase: AppDatabase

    private var mData: List<BloodPressureHistoryEntry>? = null
    private val dateFormatOld = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    private val dateFormatNew = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        appDatabase = AppDatabase.getInstance(context!!)
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    private fun initData() {
        lc_home_data_chart_1.clear()
        lc_home_data_chart_2.clear()
        lc_home_data_chart_3.clear()


        DBOptionManager.instance.executeDBOption(appDatabase.getHistoryDao()
            .getAllHistory(),
            object : DBOptionManager.Callback<List<BloodPressureHistoryEntry>>() {
                override fun onSuccess(data: List<BloodPressureHistoryEntry>?) {
                    mData = data
                    Log.i(TAG, "" + mData!!.size)
                    updateData()
                }

                override fun onFailure(error: Throwable) {
                    toast(error.message)
                }
            })


    }

    private fun toast(toastMsg: String?) {
        Toast.makeText(context, toastMsg + "", Toast.LENGTH_SHORT).show()
    }

    private fun updateData() {
        /*绘制图表*/
        if (mData!!.isEmpty()) {
            return
        }
//        lc_home_data_chart.rotation = 270f

        val entryList1 = ArrayList<Entry>()
        val entryList2 = ArrayList<Entry>()
        val entryList3 = ArrayList<Entry>()
        val xAxisIndexList = ArrayList<String>()
        for (i in 0..mData!!.size - 1) {
            var entry = mData!![i]
            entryList1.add(Entry(i.toFloat(), entry.higherValue.toFloat()))
            entryList2.add(Entry(i.toFloat(), entry.lowerValue.toFloat()))
            entryList3.add(Entry(i.toFloat(), entry.heartRate.toFloat()))
            try {
                xAxisIndexList.add(dateFormatNew.format(dateFormatOld.parse(entry.createTime)!!))
            } catch (e: Exception) {
                e.printStackTrace()
                xAxisIndexList.add(entry.createTime)
            }
        }

        val dataSet1 = LineDataSet(entryList1, "高压")
        val dataSet2 = LineDataSet(entryList2, "低压")
        val dataSet3 = LineDataSet(entryList3, "心率")

        dataSet1.color = Color.parseColor("#50F4A4")//线条颜色
        dataSet1.setCircleColor(Color.parseColor("#50F4A4"))//圆点颜色
        dataSet1.circleRadius = 0f
        dataSet1.lineWidth = 2f//线条宽度
        dataSet1.fillColor = Color.parseColor("#50F4A4")
        dataSet1.fillAlpha = 255
//        dataSet1.setDrawHorizontalHighlightIndicator(false)
//        dataSet1.setDrawVerticalHighlightIndicator(false)

        dataSet2.color = Color.parseColor("#FF7F91")//线条颜色
        dataSet2.setCircleColor(Color.parseColor("#FF7F91"))//圆点颜色
        dataSet2.circleRadius = 0f
        dataSet2.lineWidth = 2f//线条宽度
        dataSet2.fillColor = Color.parseColor("#FF7F91")
        dataSet2.fillAlpha = 255
//        dataSet2.setDrawHorizontalHighlightIndicator(false)
//        dataSet2.setDrawVerticalHighlightIndicator(false)


        dataSet3.color = Color.parseColor("#76E9FF")//线条颜色
        dataSet3.setCircleColor(Color.parseColor("#76E9FF"))//圆点颜色
        dataSet3.circleRadius = 0f
        dataSet3.lineWidth = 2f//线条宽度
        dataSet3.fillColor = Color.parseColor("#76E9FF")
        dataSet3.fillAlpha = 255
//        dataSet3.setDrawHorizontalHighlightIndicator(false)
//        dataSet3.setDrawVerticalHighlightIndicator(false)

        setChart(lc_home_data_chart_1, dataSet1, xAxisIndexList)
        setChart(lc_home_data_chart_2, dataSet2, xAxisIndexList)
        setChart(lc_home_data_chart_3, dataSet3, xAxisIndexList)

    }

    private fun setChart(
        lineChart: LineChart,
        dataSet: LineDataSet,
        xAxisIndexList: ArrayList<String>
    ) {

        val lineData = LineData(dataSet)
        lineData.setDrawValues(false)


        //设置样式
        val rightAxis = lineChart.getAxisRight()

        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false)
        lineChart.setPinchZoom(false)
        val leftAxis = lineChart.getAxisLeft()
        lineChart.animateX(300)
        lineChart.animateY(800)
        //设置图表左边的y轴禁用
        leftAxis.setEnabled(true)
        leftAxis.setTextColor(Color.BLACK)
        leftAxis.setTextSize(11f)

        leftAxis.setAxisMinimum(0f);
//        leftAxis.setDrawAxisLine(true);//是否绘制轴线
        leftAxis.setDrawGridLines(true)//设置x轴上每个点对应的线
        leftAxis.setGranularity(1f)//禁止放大后x轴标签重绘
        //设置x轴
        val xAxis = lineChart.getXAxis()
        xAxis.setTextColor(Color.BLACK)
        xAxis.setTextSize(11f)
        xAxis.setAxisMinimum(0f)
        xAxis.setDrawAxisLine(true)//是否绘制轴线
        xAxis.setDrawGridLines(false)//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true)//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM)//设置x轴的显示位置
        xAxis.setGranularity(1f)//禁止放大后x轴标签重绘


        /*设置X轴下标信息*/
        xAxis.setValueFormatter(IndexAxisValueFormatter(xAxisIndexList))


//        //透明化图例
//        val legend = lc_home_data_chart.getLegend()
//        legend.setForm(Legend.LegendForm.NONE)
//        legend.setTextColor(Color.WHITE)

//        //隐藏x轴描述
        val description = Description()
//        description.isEnabled = false
        description.text = "血压记录情况"
        lineChart.setDescription(description)

        lineChart.setData(lineData)

        var dataSets = lineChart.data.dataSets

        for (iLineDataSet in dataSets) {
            val set = iLineDataSet as LineDataSet

            set.mode = LineDataSet.Mode.CUBIC_BEZIER
            set.setDrawCircles(false)
            set.setDrawFilled(true)
        }

        lineChart.invalidate() // refresh
    }

    private fun initView() {
        btn_refresh_data.setOnClickListener {
            initData()
        }
    }
}